package user

import (
	"context"
	"strconv"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/internal/utils/errorhandler"
	"mall/service/forum/rpc/types/forum"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetUserByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetUserByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetUserByIdLogic {
	return &BackendGetUserByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetUserByIdLogic) BackendGetUserById(in *forum.ForumUserIdReq) (*forum.ForumUserInfo, error) {
	if in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	res, err := l.svcCtx.User.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var media []*forum.MediaInfo
	if in.WithMedia != nil && *in.WithMedia > 0 {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.ForumAttachmentRelationshipColumns.ObjectID] = map[string][]any{
			"equalTo": []any{in.Id},
		}
		filterMap[model.ForumAttachmentRelationshipColumns.ObjectType] = map[string][]any{
			"equalTo": []any{globalkey.ForumAttachmentTypeAvatar},
		}
		list, _, err := l.svcCtx.User.GetMedia(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 {
			for _, v := range list {
				media = append(media, &forum.MediaInfo{
					Uid:       &v.AttachmentRelationshipID,
					Id:        pointy.GetPointer(strconv.FormatInt(int64(v.AttachmentID), 10)),
					Thumbnail: pointy.GetPointer(uint32(v.AttachmentThumbnail)),
					Order:     pointy.GetPointer(uint32(v.AttachmentOrder)),
					Uri:       &v.AttachmentSource,
					Url:       &v.AttachmentImageURL,
					AltText:   &v.AttachmentImageAlt,
					MetaData:  &v.AttachmentImageMeta,
				})
			}
		}
	}

	return &forum.ForumUserInfo{
		Id:        &res.ID,
		UserId:    &res.UserID,
		NickName:  &res.UserNickname,
		Avatar:    &res.UserAvatar,
		Email:     &res.UserEmail,
		UserURL:   &res.UserURL,
		Status:    pointy.GetPointer(uint32(res.UserStatus)),
		Signature: &res.Signature,
		CreatedBy: &res.CreatedBy,
		CreatedAt: pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt: pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt: pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
		Media:     media,
	}, nil
}
